<template>
  <view class="service-page">
    <image class="page-bg" src="/static/images/service-bg.png" mode="aspectFill" />
    <CustomNavbar title="服务大厅" />
    
    <!-- 左侧固定分类导航 -->
    <view class="category-nav" :style="{ top: navBarHeight + 'px', bottom: '130rpx' }">
      <view 
        class="nav-item" 
        :class="{ active: currentCategory === 'common' }"
        @click="switchCategory('common')"
      >
        常用服务
      </view>
      <view 
        class="nav-item"
        :class="{ active: currentCategory === 'mobile' }"
        @click="switchCategory('mobile')"
      >
        手机服务类
      </view>
      <view 
        class="nav-item"
        :class="{ active: currentCategory === 'broadband' }"
        @click="switchCategory('broadband')"
      >
        宽带及ITV类
      </view>
      <view 
        class="nav-item"
        :class="{ active: currentCategory === 'general' }"
        @click="switchCategory('general')"
      >
        通用服务类
      </view>
    </view>
    
    <!-- 右侧服务内容 -->
    <view class="service-content" :style="{ paddingTop: navBarHeight + topOffset + 'px' }">
        <!-- 常用服务 -->
        <view id="common" class="service-section">
          <view class="section-header">
            <text class="section-title">常用服务</text>
            <text class="edit-btn">编辑</text>
          </view>
          <view class="service-grid">
            <view class="service-card" @click="navigateTo('/pages/bill/bill')">
              <view class="card-icon"><image src="/static/icons/icon-home5.png" alt=""/></view>
              <text class="card-label">我的账单</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/package/package')">
              <view class="card-icon"><image src="/static/icons/icon-home6.png" alt=""/></view>
              <text class="card-label">套餐余量</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/balance-detail/balance-detail')">
              <view class="card-icon"><image src="/static/icons/icon-home9.png" alt=""/></view>
              <text class="card-label">余额明细</text>
            </view>
            <view class="service-card" @click="navigateToDigitalService">
              <view class="card-icon"><image src="/static/icons/icon-home8.png" alt=""/></view>
              <text class="card-label">数字人客服</text>
            </view>
          </view>
        </view>
        
        <!-- 手机服务类 -->
        <view id="mobile" class="service-section">
          <view class="section-header">
            <text class="section-title">手机服务类</text>
          </view>
          <view class="service-grid">
            <view class="service-card" @click="navigateTo('/pages/balance-detail/balance-detail')">
              <view class="card-icon"><image src="/static/icons/icon-home9.png" alt=""/></view>
              <text class="card-label">余额明细</text>
            </view>
            <view class="service-card">
              <view class="card-icon"><image src="/static/icons/icon-home10.png" alt=""/></view>
              <text class="card-label">缴费查询</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/package/package')">
              <view class="card-icon"><image src="/static/icons/icon-home6.png" alt=""/></view>
              <text class="card-label">套餐余量</text>
            </view>
            <view class="service-card">
              <view class="card-icon"><image src="/static/icons/icon-home7.png" alt=""/></view>
              <text class="card-label">基础服务开通</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/bill/bill')">
              <view class="card-icon orange"><image src="/static/icons/icon-home5.png" alt=""/></view>
              <text class="card-label">我的账单</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/detail-query/detail-query')">
              <view class="card-icon"><image src="/static/icons/icon-home11.png" alt=""/></view>
              <text class="card-label">详单查询</text>
            </view>
            <view class="service-card" @click="navigateToInternationalRoaming">
              <view class="card-icon"><image src="/static/icons/icon-home12.png" alt=""/></view>
              <text class="card-label">国际漫游</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/sos/sos')">
              <view class="card-icon"><image src="/static/icons/icon-home13.png" alt=""/></view>
              <text class="card-label">手机紧急开机</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/value-added-unsubscribe/value-added-unsubscribe')">
              <view class="card-icon"><image src="/static/icons/icon-home14.png" alt=""/></view>
              <text class="card-label">增值业务退订</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/cost-adjustment-record/cost-adjustment-record')">
              <view class="card-icon"><image src="/static/icons/icon-home15.png" alt=""/></view>
              <text class="card-label">费用调整查询</text>
            </view>
            <view class="service-card"  @click="navigateTo('/pages/phone-fault/phone-fault')">
              <view class="card-icon"><image src="/static/icons/icon-home16.png" alt=""/></view>
              <text class="card-label">手机报障</text>
            </view>
            <view class="service-card">
              <view class="card-icon"><image src="/static/icons/icon-home17.png" alt=""/></view>
              <text class="card-label">复开机</text>
            </view>
            <view class="service-card">
              <view class="card-icon"><image src="/static/icons/icon-home18.png" alt=""/></view>
              <text class="card-label">查询PUK</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/complaint-progress/complaint-progress')">
              <view class="card-icon"><image src="/static/icons/icon-home19.png" alt=""/></view>
              <text class="card-label">解挂</text>
            </view>
          </view>
        </view>
        
        <!-- 宽带及ITV类 -->
        <view id="broadband" class="service-section">
          <view class="section-header">
            <text class="section-title">宽带及ITV类</text>
          </view>
          <view class="service-grid">
            <view class="service-card" @click="navigateTo('/pages/broadband-fault/broadband-fault')">
              <view class="card-icon"><image src="/static/icons/icon-home20.png" alt=""/></view>
              <text class="card-label">宽带报障</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/guhua-baoz/guhua-baoz')">
              <view class="card-icon"><image src="/static/icons/icon-home21.png" alt=""/></view>
              <text class="card-label">固话服务</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/itv-value-added/itv-value-added')">
              <view class="card-icon"><image src="/static/icons/icon-home22.png" alt=""/></view>
              <text class="card-label">ITV服务</text>
            </view>
            <view class="service-card">
              <view class="card-icon"><image src="/static/icons/icon-home23.png" alt=""/></view>
              <text class="card-label">宽带密码重置</text>
            </view>
            <view class="service-card">
              <view class="card-icon"><image src="/static/icons/icon-home24.png" alt=""/></view>
              <text class="card-label">ITV业务退订</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/complaint-submit/complaint-submit')">
              <view class="card-icon"><image src="/static/icons/icon-home25.png" alt=""/></view>
              <text class="card-label">WIFI密码修改/投诉</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/complaint-submit/complaint-submit')">
              <view class="card-icon"><image src="/static/icons/icon-home25.png" alt=""/></view>
              <text class="card-label">投诉</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/diagnosis/diagnosis')">
              <view class="card-icon"><image src="/static/icons/icon-home25.png" alt=""/></view>
              <text class="card-label">一键诊断</text>
            </view>
          </view>
        </view>
        
        <!-- 通用服务类 -->
        <view id="general" class="service-section">
          <view class="section-header">
            <text class="section-title">通用服务类</text>
          </view>
          <view class="service-grid">
            <view class="service-card" @click="navigateToPointsExchange">
              <view class="card-icon blue"><image src="/static/icons/icon-home26.png" alt=""/></view>
              <text class="card-label">积分兑换</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/invoice/invoice')">
              <view class="card-icon blue"><image src="/static/icons/icon-home27.png" alt=""/></view>
              <text class="card-label">电子发票</text>
            </view>
            <view class="service-card" @click="navigateToServiceHall">
              <view class="card-icon blue"><image src="/static/icons/icon-home28.png" alt=""/></view>
              <text class="card-label">营业厅查询</text>
            </view>
            <view class="service-card" @click="navigateToFraudReport">
              <view class="card-icon blue"><image src="/static/icons/icon-home29.png" alt=""/></view>
              <text class="card-label">诈骗举报</text>
            </view>
            <view class="service-card" @click="navigateToOneCertificateQuery">
              <view class="card-icon blue"><image src="/static/icons/icon-home30.png" alt=""/></view>
              <text class="card-label">一证通查</text>
            </view>
            <view class="service-card" @click="navigateToSecondaryRealNameAuth">
              <view class="card-icon blue"><image src="/static/icons/icon-home31.png" alt=""/></view>
              <text class="card-label">二次实人认证</text>
            </view>
            <view class="service-card" @click="navigateToVideoCustomerService">
              <view class="card-icon blue"><image src="/static/icons/icon-home32.png" alt=""/></view>
              <text class="card-label">视频客服</text>
            </view>
            <view class="service-card" @click="navigateTo('/pages/complaint-progress/complaint-progress')">
              <view class="card-icon blue"><image src="/static/icons/icon-home29.png" alt=""/></view>
              <text class="card-label">投诉进度查询</text>
            </view>
          </view>
        </view>
    </view>
    <CustomTabBar current="/pages/service/service" />
  </view>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { onPageScroll } from '@dcloudio/uni-app'
import CustomNavbar from '@/components/CustomNavbar.vue'
import CustomTabBar from '@/components/CustomTabBar.vue'
import { api } from '@/utils/api.js'
import { useUserStore } from '@/store/user.js'

const currentCategory = ref('common')
const navBarHeight = ref(88) // 默认值：状态栏(44) + 导航栏(44)
const topOffset = ref(15) // 距离顶部的额外距离（px）
const isScrolling = ref(false) // 防止滚动时频繁更新
const userStore = useUserStore()

onMounted(() => {
  // 获取导航栏高度
  const windowInfo = uni.getWindowInfo()
  const statusBarHeight = windowInfo.statusBarHeight || 0
  navBarHeight.value = statusBarHeight + 44
})

// 监听页面滚动，更新当前分类
onPageScroll(() => {
  if (isScrolling.value) return // 如果正在滚动切换，不更新
  
  uni.createSelectorQuery().selectAll('.service-section').boundingClientRect((rects) => {
    if (!rects || rects.length === 0) return
    
    const viewportTop = navBarHeight.value + topOffset.value
    
    // 找到当前在视口顶部的分类
    for (let i = 0; i < rects.length; i++) {
      const rect = rects[i]
      if (rect.top <= viewportTop + 50 && rect.top + rect.height > viewportTop) {
        const categoryMap = {
          'common': 'common',
          'mobile': 'mobile',
          'broadband': 'broadband',
          'general': 'general'
        }
        const categoryId = rect.id
        if (categoryMap[categoryId] && currentCategory.value !== categoryId) {
          currentCategory.value = categoryId
        }
        break
      }
    }
  }).exec()
})

const switchCategory = (category) => {
  if (currentCategory.value === category) return
  
  currentCategory.value = category
  isScrolling.value = true
  
  nextTick(() => {
    // 使用 uni.createSelectorQuery 获取目标元素位置
    uni.createSelectorQuery().select(`#${category}`).boundingClientRect((rect) => {
      if (rect) {
        // 获取当前滚动位置
        uni.createSelectorQuery().selectViewport().scrollOffset((scroll) => {
          // 计算需要滚动的距离（考虑导航栏高度和顶部偏移）
          const targetScrollTop = scroll.scrollTop + rect.top - navBarHeight.value - topOffset.value
          
          uni.pageScrollTo({
            scrollTop: Math.max(0, targetScrollTop),
            duration: 300,
            success: () => {
              setTimeout(() => {
                isScrolling.value = false
              }, 350)
            },
            fail: () => {
              isScrolling.value = false
            }
          })
        }).exec()
      } else {
        isScrolling.value = false
      }
    }).exec()
  })
}

const navigateTo = (url) => {
  console.log('准备跳转到:', url)
  wx.navigateTo({ 
    url,
    success: (res) => {
      console.log('跳转成功:', res)
    },
    fail: (err) => {
      console.error('跳转失败:', err, '目标路径:', url)
      uni.showToast({
        title: '跳转失败: ' + (err.errMsg || '未知错误'),
        icon: 'none',
        duration: 2000
      })
    }
  })
}

// 跳转到数字人客服
const navigateToDigitalService = async () => {
  try {
    // 获取手机号
    const userInfo = uni.getStorageSync('userInfo')
    const phone = userStore.phone || userInfo?.phone || '18124058091'
    
    if (!phone) {
      uni.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 2000
      })
      return
    }
    
    // 显示加载提示
    uni.showLoading({
      title: '加载中...',
      mask: true
    })
    
    // 调用接口获取数字人客服URL
    const res = await api.getSzrUrl(phone)
    
    uni.hideLoading()
    
    if (res.code === 200 && res.msg) {
      const targetUrl = res.msg
      
      // 跳转到返回的URL
      // #ifdef H5
      window.location.href = targetUrl
      // #endif
      
      // #ifdef MP-WEIXIN
      // 小程序中需要通过 web-view 打开外部链接
      // 注意：需要在 manifest.json 中配置业务域名 szr.ai.chinatelecom.cn
      // 使用相对路径跳转到包含 web-view 的页面
      uni.navigateTo({
        url: 'https://szr.ai.chinatelecom.cn:8093/#/pages/login/loadingLogin?token=f980bb00-cc3f-406f-a23c-9227c9a86cc2',
        success: () => {
          console.log('跳转到 web-view 页面成功')
        },
        fail: (err) => {
          console.error('跳转失败:', err)
          // 如果相对路径失败，尝试绝对路径
          uni.navigateTo({
            url: `/pages/link/link?lurl=${encodeURIComponent(targetUrl)}`,
            fail: (err2) => {
              console.error('绝对路径跳转也失败:', err2)
              uni.showToast({
                title: '跳转失败，请检查配置',
                icon: 'none',
                duration: 2000
              })
            }
          })
        }
      })
      // #endif
      
      // #ifdef APP-PLUS
      plus.runtime.openURL(targetUrl)
      // #endif
    } else {
      throw new Error(res.msg || '获取客服链接失败')
    }
  } catch (error) {
    uni.hideLoading()
    console.error('跳转数字人客服失败:', error)
    uni.showToast({
      title: error.message || '获取客服链接失败，请重试',
      icon: 'none',
      duration: 2000
    })
  }
}

/**
 * 通用外链接跳转方法
 * 支持 H5 和小程序平台
 * @param {string} url - 目标网页地址（必须是完整的 https:// 或 http:// 开头的 URL）
 * @param {string} title - 小程序中 web-view 页面的标题（可选，默认为"网页"）
 */
const navigateToExternalUrl = (url, title = '网页') => {
  if (!url) {
    console.error('navigateToExternalUrl: url 参数不能为空')
    uni.showToast({
      title: '链接地址不能为空',
      icon: 'none',
      duration: 2000
    })
    return
  }

  // 确保 URL 是完整的地址
  if (!url.startsWith('http://') && !url.startsWith('https://')) {
    console.error('navigateToExternalUrl: url 必须是完整的 http:// 或 https:// 地址')
    uni.showToast({
      title: '链接地址格式错误',
      icon: 'none',
      duration: 2000
    })
    return
  }

  // #ifdef H5
  // H5 端：直接使用 window.location 跳转
  try {
    window.location.href = url
  } catch (error) {
    console.error('H5 跳转失败:', error)
    uni.showToast({
      title: '跳转失败',
      icon: 'none',
      duration: 2000
    })
  }
  // #endif

  // #ifdef MP-WEIXIN
  // 微信小程序：通过 web-view 组件打开外部链接
  // 注意：需要在微信公众平台配置业务域名 kf.xj.189.cn
  uni.navigateTo({
    url: `/pages/link/link?lurl=${encodeURIComponent(url)}&title=${encodeURIComponent(title)}`,
    success: (res) => {
      console.log('跳转到 web-view 页面成功:', res)
    },
    fail: (err) => {
      console.error('跳转失败:', err)
      uni.showToast({
        title: '跳转失败，请检查业务域名配置',
        icon: 'none',
        duration: 2000
      })
    }
  })
  // #endif

  // #ifdef APP-PLUS
  // App 端：使用 plus.runtime.openURL 打开外部浏览器
  try {
    plus.runtime.openURL(url, (err) => {
      if (err) {
        console.error('App 打开外部链接失败:', err)
        uni.showToast({
          title: '打开链接失败',
          icon: 'none',
          duration: 2000
        })
      }
    })
  } catch (error) {
    console.error('App 跳转异常:', error)
  }
  // #endif
}

// 跳转到积分兑换
const navigateToPointsExchange = () => {
  navigateToExternalUrl('https://kf.xj.189.cn/xjwechat/serviceHall/pointMall', '积分兑换')
}

// 跳转到国际漫游
const navigateToInternationalRoaming = () => {
  navigateToExternalUrl('https://kf.xj.189.cn/xjwechat/serviceHall/internationalRoaming', '国际漫游')
}

// 跳转到营业厅查询
const navigateToServiceHall = () => {
  navigateToExternalUrl('https://kf.xj.189.cn/xjwechat/serviceHall/nearbyServiceHall', '营业厅查询')
}

// 跳转到诈骗举报
const navigateToFraudReport = () => {
  navigateToExternalUrl('https://kf.xj.189.cn/xjwechat/serviceHall/fraudReport', '诈骗举报')
}

// 跳转到一证通查
const navigateToOneCertificateQuery = () => {
  navigateToExternalUrl('https://kf.xj.189.cn/xjwechat/serviceHall/oneCertificateQuery', '一证通查')
}

// 跳转到二次实人认证
const navigateToSecondaryRealNameAuth = () => {
  navigateToExternalUrl('https://kf.xj.189.cn/xjwechat/serviceHall/secondaryRealNameAuth', '二次实人认证')
}

// 跳转到视频客服
const navigateToVideoCustomerService = () => {
  navigateToExternalUrl('https://kf.xj.189.cn/xjwechat/serviceHall/videoCustomerService', '视频客服')
}
</script>

<style scoped>
.service-page {
   
  position: relative;
  z-index: 1;
}

.page-bg {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  z-index: -1;
  pointer-events: none;
  object-fit: cover;
}

/* 左侧固定导航 */
.category-nav {
  position: fixed;
  left: 0;
  width: 126rpx;
  background: rgba(212, 230, 249, 1);
  border-right: 1rpx solid #F0F0F0;
  z-index: 100;
  overflow-y: auto;
  overflow-x: hidden;
}

.nav-item {
      padding: 24rpx 20rpx;
    font-size: 28rpx;
    color: #666;
    text-align: center;
    border-left: 2rpx solid transparent;
    transition: all 0.3s ease;
}

.nav-item.active {
  color: #4A90E2;
  background: rgba(243, 247, 253, 1);
  border-left-color: #4A90E2;
}

/* 右侧服务内容 */
.service-content {
  margin-left: 126rpx;
  padding: 0 32rpx;
  padding-bottom: 230rpx;
   
}

.service-section {
  /* background: #fff; */
  border-radius: 20rpx;
  /* padding: 30rpx; */
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* margin-bottom: 30rpx; */
}

.section-title {
  color: rgba(51, 51, 51, 1);
font-family: HarmonyOS Sans SC;
font-size: 32rpx;
font-weight: 500;
line-height: 38rpx;
padding: 40rpx 0 32rpx 0;
}

.edit-btn {
  font-size: 28rpx;
  color: #4A90E2;
}

.service-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 24rpx;
  background: rgba(255, 255, 255, 0.4);
  border-radius: 16rpx;
  padding: 40rpx 24rpx;
}

.service-card {
  width: calc(25% - 22.5rpx);
  display: flex;
  flex-direction: column;
  align-items: center;
}

.card-icon {
  width: 62rpx;
  height: 62rpx;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 48rpx;
  margin-bottom: 15rpx;
}
.card-icon image {
  width: 62rpx;
  height: 62rpx;
}


.card-label {
  font-size: 24rpx;
  color: #666;
  text-align: center;
}
</style>

